<template>
	<el-dialog title="考勤打卡对话框" v-model="visible" customClass="customWidth" destroy-on-close @closed="$emit('closed')">
		<el-form :model="form" ref="dialogForm" label-width="100px" label-position="left">
			<div style="text-align: center;font-weight: 600;font-size: 18px;">{{ config.title }}</div>
			<div style="text-align: center;font-weight: 600;font-size: 18px;">{{ this.config.beginTime }}~{{ this.config.endTime }}</div>
			<div style="font-weight: 600;font-size: 18px;">经度:{{form.longitude}}</div>
			<div style="font-weight: 600;font-size: 18px;">纬度:{{form.latitude}}</div>
			<div style="font-weight: 600;font-size: 18px;margin-bottom: 10px">地址:{{form.address}}</div>
			<div style="font-weight: 600;font-size: 18px;margin-bottom: 10px">
				<sapn v-if="this.testRes.res==false">
					范围:距离打卡点<span style="color:orangered;">{{testRes.distance}}</span>米
				</sapn>
				<sapn v-if="this.testRes.res==true">
					范围:<span style="color: #67c23a">已在打卡范围内</span>
				</sapn>
			</div>
			<el-input v-model="form.remark" placeholder="打卡说明" clearable maxlength="380" type="textarea"></el-input>
			<div style="text-align: center;margin-top: 10px;margin-bottom: 10px;">
				<el-button type="primary" @click="toWork">上班打卡</el-button>
				<el-button type="success" @click="offWork">下班打卡</el-button>
			</div>
		</el-form>
	</el-dialog>
</template>
<script>
import sha1 from 'js-sha1'
import jWeixin from 'weixin-jsapi';
import {calculateDistance} from "@/utils/util";
export default {
	emits: ['success', 'closed'],
	components: {},
	data() {
		return {
			visible: false,
			isSaveing: false,
			onStatus:1,
			offStatus:1,
			testRes:{},
			config: {},
			accessToken:'',
			jsTicket:'',
			corpId:'',
			form: {
				configId:"",
				address:"",
				status:'',
				longitude: '',
				latitude: '',
				source:'wx',
				remark: ''
			},
			rules: {
			},
		}
	},
	mounted() {
		this.getAttendStatusDay();
		this.getOffWorkAttendStatusDay();
	},
	methods: {
		//显示
		open() {
			this.visible = true;
			return this
		},
		submit() {
			//加载树数据
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					var res = await this.$API.office.attend.insertAttend.post(this.form);
					this.isSaveing = false;
					if (res.code == 200) {
						this.$message.success("操作成功")
					} else {
						this.$alert(res.message, "提示", {type: 'error'})
					}
				}
			})
		},
		setData(data) {
			this.form.configId = data.configId;
			this.accessToken = data.accessToken;
			this.corpId = data.corpId;
			this.getAttendConfigById();
		},
		async doGetLocation(accessToken) {
			let _this = this;
			var res = await this.$API.chat.weiXin.getWxJSAPITicket.get({accessToken: accessToken});
			if (res.code == 200) {
				this.jsTicket = res.data.ticket;
				let timestamp = this.getTimestamp();
				let nonceStr = this.randomString(16)
				await jWeixin.config({
					debug: false, // 调试时可开启
					appId: _this.corpId, // 必填，企业微信的应用id （e.g. 1000247）
					timestamp: timestamp,
					nonceStr: nonceStr,
					signature: this.getSignature(this.jsTicket, nonceStr, timestamp),
					jsApiList: [
						'getLocation'
					],
					success: function(res) {
						console.log(res, '回调res');
					},
					fail: function(res) {
						if (res.errMsg.indexOf('function not exist') > -1) {
							alert('版本过低请升级')
						} else {
							alert('请授权')
						}
					}
				});
				jWeixin.ready(function() {
					jWeixin.getLocation({
						type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
						success: function (res) {
							_this.form.latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
							_this.form.longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
							_this.testRes=calculateDistance(res.latitude, res.longitude,_this.config.lat,_this.config.lon,_this.config.disc)
							_this.showPositions(res.latitude, res.longitude)
						}
					});
				});
				jWeixin.error(function(res) {
					console.log(res, '失败');
				});
				jWeixin.checkJsApi({
					jsApiList: ['getLocation'], // 需要检测的JS接口列表
					success: function(res) {
						//alert("bbb:"+res.errMsg);
						console.log(res, '是否可以');
					}
				});
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
		async showPositions(lat, lng)
		{
			var res = await this.$API.system.mobileNet.getLocation.get({lat: lat,lng:lng});
			if (res.code == 200) {
				this.form.address = res.data.result.formatted_address;
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
		async getAttendConfigById() {
			var res = await this.$API.system.attendConfig.getAttendConfigById.get({configId: this.form.configId});
			if (res.code == 200) {
				this.config = res.data;
				this.doGetLocation(this.accessToken);
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
		getTimestamp() {
			return Date.parse(new Date());
		},
		randomString(len) {
			len = len || 32
			var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
			var maxPos = $chars.length
			var pwd = ''
			for (var i = 0; i < len; i++) {
				pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
			}
			return pwd
		},
		getSignature(ticket, noncestr, timestamp) {
			let url = window.location.href.split("#")[0]
			let jsapi_ticket = `jsapi_ticket=${
				ticket}&noncestr=${
				noncestr}&timestamp=${
				timestamp}&url=${
				url}`;
			return sha1(jsapi_ticket);
		},
		async toWork()
		{
			if(this.onStatus=='1')
			{
				this.$alert('不能重复打卡', "提示", {type: 'error'})
			}else {
				if(this.form.latitude==''||this.form.longitude=='')
				{
					this.$alert("没有正确获取到位置信息！", "提示", {type: 'error'})
					return false;
				}else
				{
					if(this.testRes.res==false)
					{
						this.$alert('不在打卡范围内', "提示", {type: 'error'})
					}else {
						this.form.status = '1';
						var res = await this.$API.office.attend.insertAttend.post(this.form);
						if (res.code == 200) {
							this.onStatus = "1";
							this.$message.success("打卡成功");
						} else {
							this.$alert(res.message, "提示", {type: 'error'})
						}
					}
				}
				this.visible = false;
			}
		},
		async offWork()
		{
			if(this.offStatus=='1')
			{
				this.$alert('不能重复打卡', "提示", {type: 'error'})
			}else {
				if (this.form.latitude == '' || this.form.longitude == '') {
					this.$alert("没有正确获取到位置信息！", "提示", {type: 'error'})
					return false;
				} else {
					if(this.testRes.res==false)
					{
						this.$alert('不在打卡范围内', "提示", {type: 'error'})
					}else {
						this.form.status = '2';
						var res = await this.$API.office.attend.insertAttend.post(this.form);
						if (res.code == 200) {
							this.offStatus = "0";
							this.$message.success("打卡成功");
						} else {
							this.$alert(res.message, "提示", {type: 'error'})
						}
					}
				}
				this.visible = false;
			}
		},
		async getAttendStatusDay()
		{
			var res = await this.$API.office.attend.getAttendStatusDay.get();
			if (res.code == 200) {
				this.onStatus = res.data.status;
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
		async getOffWorkAttendStatusDay()
		{
			var res = await this.$API.office.attend.getOffWorkAttendStatusDay.get();
			if (res.code == 200) {
				this.offStatus = res.data.status;
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
	}
}
</script>

<style>
.customWidth {
	width: 60%;
}
</style>
